from tkinter import font
from B_Data import *
from D_Individual import *

import numpy as np
import B_Data
import E_SetAdp
from matplotlib import pyplot as plt, axes, font_manager
import matplotlib
from mpl_toolkits.mplot3d import Axes3D

Zh_Font = matplotlib.font_manager.FontProperties(fname="venv/include/SourceHanSansSC-Bold.otf")
plt.rc('font', family='Times New Roman')
plt.rc('font', size=16)
plt.rc('font', weight='bold')
legend_font = {
    'fname': 'C:/Windows/fonts/simhei.ttf',  # 引用系统字体
    'style': 'normal',
    'size': 14,  # 字号
    'weight': "normal",  # 是否加粗，不加粗
}
# 画甘特图
def Draw_Gatt_New(PS_Chromosome,LS_Chromosome,PC_DS):

    plt.figure(figsize=(25, 8))
    M = ['dimgray', 'tan', 'darkgreen', 'royalblue', 'lightcoral', 'gold', 'lightseagreen',
         'blue', 'red', 'darkslategrey', 'darkviolet', 'orangered', 'yellow', 'deepskyblue',
         'fuchsia', 'saddlebrown', 'lawngreen', 'dodgerblue', 'lightgreen', 'pink']
    # 遍历每个构件
    for index in range(len(PS_Chromosome)):
        PC_Code = PS_Chromosome[index]

        Process_Len = len(PC_DS[PC_Code][2])  # 持续时间
        # 遍历构件的每个工序
        for Process_Index in range(Process_Len):
            Start_time = PC_DS[PC_Code][0][Process_Index]  # 开始时间
            End_time   = PC_DS[PC_Code][1][Process_Index]  # 结束时间
            Last_Time  = PC_DS[PC_Code][2][Process_Index]  # 持续时间
            plt.barh(index, width=Last_Time, left=Start_time, color=M[Process_Index], edgecolor='white')   # 工序（每个）甘特图：x轴数据，宽度，起始位置，颜色，边缘）
            plt.text(x=Start_time-0.3 + Last_Time/2, y=index-0.1, s=str(index+1) + '-' + str(Process_Index+1))  # 工序（每个）甘特图：x位置，y位置，text字符串
    plt.xticks(np.arange(0, 25, 1), fontsize=15, fontproperties=Zh_Font)  # np.arange(0,27,1)
    plt.yticks(np.arange(len(PS_Chromosome)), PS_Chromosome, fontsize=15, fontproperties=Zh_Font)  # B_Data.Production_Line
    plt.title("构件生产调度甘特图", fontsize=20, fontproperties=Zh_Font)
    plt.legend(B_Data.Production_class, fontsize=20, frameon=False, prop=legend_font, bbox_to_anchor=(1.01, 0.36), loc=3, borderaxespad=0)
    plt.ylabel('构件编号', fontsize=17, fontproperties=Zh_Font)
    plt.xlabel('单位生产时间', fontsize=17, fontproperties=Zh_Font)
    plt.show()




# 画甘特图
# def Draw_Gatt_Me(Idv,DataStructure):
#
#     plt.figure(figsize=(25, 8))
#     M = ['dimgray', 'tan', 'darkgreen', 'royalblue', 'lightcoral', 'gold', 'lightseagreen',
#          'blue', 'red', 'darkslategrey', 'darkviolet', 'orangered', 'yellow', 'deepskyblue',
#          'fuchsia', 'saddlebrown', 'lawngreen', 'dodgerblue', 'lightgreen', 'pink']
#
#     # 构件 和 生产线
#     PS_Chromosome = Idv.PS_Chromosome
#     LS_Chromosome = Idv.LS_Chromosome
#
#     PC_DataStructures = DataStructure.PC_DataStructure
#     print("PC_DataStructure::",PC_DataStructures)
#
#     # 遍历每个构件
#     for index in range(len(PS_Chromosome)):
#         PC_Code = PS_Chromosome[index]
#         PC_Detail = PC_DataStructures[PC_Code]
#
#         Process_Len = len(PC_Detail[0])
#         # 遍历构件的每个工序
#         for Process_Index in range(Process_Len):
#             Last_Time  = PC_Detail[0][Process_Index]  # 持续时间
#             Start_time = PC_Detail[1][Process_Index]  # 开始时间
#             End_time   = PC_Detail[2][Process_Index]  # 结束时间
#             plt.barh(index, width=Last_Time, left=Start_time, color=M[Process_Index], edgecolor='white')   # 工序（每个）甘特图：x轴数据，宽度，起始位置，颜色，边缘）
#             plt.text(x=Start_time-0.3 + Last_Time/2, y=index-0.1, s=str(index+1) + '-' + str(Process_Index+1))  # 工序（每个）甘特图：x位置，y位置，text字符串
#     plt.xticks(np.arange(0, 30, 1), fontsize=15, fontproperties=Zh_Font)  # np.arange(0,27,1)
#     plt.yticks(np.arange(4), PS_Chromosome, fontsize=15, fontproperties=Zh_Font)  # B_Data.Production_Line
#     plt.title("构件生产调度甘特图", fontsize=20, fontproperties=Zh_Font)
#     plt.legend(B_Data.Production_class, frameon=False, prop=legend_font, bbox_to_anchor=(1.01, 0.36), loc=3,
#                borderaxespad=0)
#     plt.ylabel('生产线', fontsize=17, fontproperties=Zh_Font)
#     plt.xlabel('时间', fontsize=17, fontproperties=Zh_Font)
#     plt.show()

def Draw_Gatt_Me_Points_1d(x):
    plt.figure(figsize=(20, 10))
    ypoint = x
    plt.xticks(np.arange(0, len(x), 100), fontsize=18, fontproperties=Zh_Font)
    plt.title("完工时间", fontsize=30, fontproperties=Zh_Font)
    plt.ylabel('完工时间', fontsize=20, fontproperties=Zh_Font)
    plt.xlabel('个体', fontsize=20, fontproperties=Zh_Font)
    plt.plot(ypoint, marker='*')
    plt.show()


def Draw_Gatt_Me_Points_2d(x, y):
    plt.figure(figsize=(20, 10))

    plt.xticks(np.arange(0, max(x)+5, 10), fontsize=18, fontproperties=Zh_Font)
    plt.yticks(np.arange(0, max(y)+5, 10), fontsize=18, fontproperties=Zh_Font)
    plt.title("2D Time Scatter Plot", fontsize=30, fontproperties=Zh_Font)
    plt.ylabel('Critical Line Loads', fontsize=20, fontproperties=Zh_Font)
    plt.xlabel('Minimum completion time', fontsize=20, fontproperties=Zh_Font)

    plt.scatter(x, y, s=100)
    plt.show()

def Draw_Gatt_Me_Points_2d_sort(x, y, Nodominate_Ship):
    Nodominate_Ship_sort = []
    print(x)
    print(y)
    for i in range(len(Nodominate_Ship)):
        a = Nodominate_Ship[i]
        for j in range(len(a)):
            for k in range(j+1,len(a)):
                if(x[a[j]] > x[a[k]]):
                    t = a[j]
                    a[j] = a[k]
                    a[k] = t
        Nodominate_Ship_sort.append(a)
        # print(Nodominate_Ship_sort)


    plt.figure(figsize=(20, 10))

    plt.xticks(np.arange(0, max(x) + 5, 10), fontsize=18, fontproperties=Zh_Font)
    plt.yticks(np.arange(0, max(y) + 5, 10), fontsize=18, fontproperties=Zh_Font)
    plt.title("2D Time Scatter Plot", fontsize=30, fontproperties=Zh_Font)
    plt.ylabel('Critical Line Loads', fontsize=20, fontproperties=Zh_Font)
    plt.xlabel('Minimum completion time', fontsize=20, fontproperties=Zh_Font)
    Color = ['pink', 'tan', 'red', 'black','darkgreen', 'royalblue', 'lightcoral']
    Size  = [80, 90, 100, 110]
    color = ['pink']*len(x)
    size = [100]*len(x)
    print(color)
    for i in range(len(Nodominate_Ship)):  # 同一组的个体
        for j in range(len(Nodominate_Ship[i])):
            index = Nodominate_Ship_sort[i][j]
            color[index] = Color[i % len(Color)]
            size[index] = Size[i % len(Size)]
            if(j < len(Nodominate_Ship_sort[i])-1):
                # plt.plot(点坐标，点坐标，颜色)
                plt.plot([x[Nodominate_Ship_sort[i][j]],x[Nodominate_Ship_sort[i][j+1]]], [y[Nodominate_Ship_sort[i][j]],y[Nodominate_Ship_sort[i][j+1]]], color[index])
    print(color)
    for a, b in zip(x, y):  # 添加这个循环显示坐标
        # plt.text（x值，y值，（坐标格式），位置，位置，大小）bottom
        plt.text(a, b, (a,b), ha='center', va='bottom', fontsize=13)
    plt.scatter(x, y, c=color, s=size)
    plt.show()

def Draw_Gatt_Me_Points_3d(x, y, z):
    plt.figure(figsize=(18, 10))

    # 绘制散点图

    # 创建3d绘图区域
    ax = plt.axes(projection='3d')
    # 添加数据
    X_Data = x
    Y_Data = y
    Z_Data = z

    # 添加坐标轴
    ax.set_zlabel('总生产线负载', fontdict={'size': 15, 'color': 'red'}, fontproperties=Zh_Font)
    ax.set_ylabel('关键生产线负载', fontdict={'size': 15, 'color': 'red'}, fontproperties=Zh_Font)
    ax.set_xlabel('最短完工时间', fontdict={'size': 15, 'color': 'red'}, fontproperties=Zh_Font)
    plt.title("三维时间散点图", fontsize=17, fontproperties=Zh_Font)

    ax.scatter3D(X_Data, Y_Data, Z_Data, zdir="z", c="#00DDAA", marker="^", s=40)
    plt.show()

def test():
    x = np.array([1, 2, 3,  4, 5,  6,  7,  8])
    y = np.array([1, 4, 9, 16, 7, 11, 23, 18])
    color =[ 'pink','pink','tan','tan','red','red','#00DDDA','#00DDDA']
    sizes = np.array([20, 50, 100, 200, 500, 1000, 60, 90])
    plt.scatter(x, y, c=color,s=sizes)
    plt.show()


# 单个个体的测试，包括画图，可以在这个地方测试
if __name__ == "__main__":
    # 初始化数据集（公共）
    DataStructure = C_Load_Process_Map.Load_Process_Map_Me()
    # 初始化个体
    Idv = Individual()
    PS_Chromosome = ['PC_0_01_0', 'PC_0_02_0', 'PC_0_03_0', 'PC_0_02_1']
    LS_Chromosome = ['1#', '2#', '1#', '2#']
    # 适应度函数计算
    Idv.Update_Chromosome(PS_Chromosome, LS_Chromosome, DataStructure)
    # 画图
    Draw_Gatt_Me(Idv,DataStructure)
